package com.cn.zengzeng.spbzengzeng.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cn.zengzeng.spbzengzeng.po.UserPo;
import com.cn.zengzeng.spbzengzeng.service.AccountService;
import com.cn.zengzeng.spbzengzeng.service.UserAccountService;
import com.cn.zengzeng.spbzengzeng.utils.AESUtils;
import com.cn.zengzeng.spbzengzeng.utils.CheckUtils;
import com.cn.zengzeng.spbzengzeng.utils.JwtUtils;
import com.cn.zengzeng.spbzengzeng.vo.ActionResult;
import com.github.benmanes.caffeine.cache.Cache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.websocket.server.PathParam;

/**
 * 用户登录相关
 * @Author: ZhangZengZeng
 * @Date: 2022/12/1 23:33
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class LoginController {

    @Resource
    private AccountService accountService ;

    @Resource
    private UserAccountService userAccountService ;
    @Resource
    private Cache<String,Object> cache ;
    @Resource
    private RabbitTemplate rabbitTemplate ;
    /**
    * 登录
    * @author ZhangZengZeng
    * @date 2022/12/1 23:36
    * @param jsonObject  登录参数
    * @return {@link ActionResult}
    */
    @PostMapping(value = "/accountLogin")
    public ActionResult accountLogin(@RequestBody JSONObject jsonObject){
        String account = jsonObject.getString("account");
        String password = jsonObject.getString("password");
        String decrypt = AESUtils.encrypt(password);
        log.info("accountLogin请求参数用户:{},密码:{}",account,decrypt);
        UserPo userPo = userAccountService.selectAccount(account);
        if(userPo==null){
            return ActionResult.getSuccessResult("5010",null);
        }else {
            String poPassword = userPo.getPassword();
            String sign = JwtUtils.sign(account);
            JSONObject data = new JSONObject();
            data.put("token",sign);
            if(poPassword.equals(decrypt)){
                return ActionResult.getSuccessResult("200",data);
            }else {
                return ActionResult.getSuccessResult("5011",null);
            }
        }
    }

    /**
    * 注册
    * @author ZhangZengZeng
    * @date 2022/12/1 23:36
    * @param userPo  注册参数
    * @return {@link ActionResult}
    */
    @PostMapping(value = "/accountRegister")
    public ActionResult accountRegister(@Valid @RequestBody UserPo userPo){
        long str = System.currentTimeMillis();
        try {
            log.info("accountRegister请求参数:{}",JSON.toJSONString(userPo));
            ActionResult successResult = accountService.getRegisterAction(userPo);
            if(successResult != null) {
                return successResult;
            }
        }finally {
            long end = System.currentTimeMillis();
            log.info("accountRegister执行耗时:{} ms",end-str);
        }
        return ActionResult.getSuccessResult("3000",null);
    }



    /**
    * 忘记密码 找回密码
    * @author ZhangZengZeng
    * @date 2022/12/1 23:37
    * @param request 忘记密码参数
    * @return {@link ActionResult}
    */
    @PostMapping(value = "/accountUpPass")
    public ActionResult accountUpPass(@RequestBody JSONObject request){
        String email = request.getString("email");
        String account = request.getString("account");
        String password = request.getString("password");
        String encrypt = AESUtils.encrypt(password);
        log.info("accountUpPass 请求参数 account:{}, email:{}, 加密后密码:{}",account,email,encrypt);
        if(CheckUtils.checkEmail(email)){
            log.info("accountUpPass 通过邮箱找回");
            // 忘记密码 修改
            boolean b = userAccountService.upPassWordByEmail(email,encrypt);
            if(b){
                return ActionResult.getSuccessResult("200");
            }
        }else {
            log.info("accountUpPass 通过账号找回");
            boolean b = userAccountService.upPassWord(account,encrypt);
            if(b){
                return ActionResult.getSuccessResult("200");
            }
        }
        return ActionResult.getSuccessResult("403");
    }

    /**
    * 激活账号
    * @author ZhangZengZeng
    * @date 2023/3/31 17:05
    * @param account 参数
    * @return {@link ActionResult}
    */
    @GetMapping(value = "/activeAccount/{account}")
    public ActionResult activeAccount(@PathVariable(name = "account") String account){
        log.info("激活账号:{}",account);
        UserPo userPo = userAccountService.selectAccount(account);
        if(userPo!=null){
            int status = userPo.getStatus();
            if(1==status){
                log.info("账号:{}重复请求激活!",account);
                return ActionResult.getSuccessResult("5008");
            }
        }
        String o = (String) cache.asMap().get("ACTIVE" + account);
        //在激活的时间范围内
        if(o!=null){
            boolean b = userAccountService.activeAccount(account);
            log.info("账号:{}激活返回!",account);
            if(b){
                return ActionResult.getSuccessResult("200");
            }
            return ActionResult.getSuccessResult("5006");
        }
        return ActionResult.getSuccessResult("5007");
    }

    /**
    * 用户信息修改
    * @author ZhangZengZeng
    * @date 2023/3/31 17:06
    * @param request  参数
    * @return {@link ActionResult}
    */
    @PostMapping(value = "/upAccountInfo")
    public ActionResult upAccountInfo(@RequestBody JSONObject request){
        log.info("upAccountInfo请求参数:{}",JSON.toJSONString(request));
        return new ActionResult();
    }

    @PostMapping(value = "/upAccountPassword")
    @Transactional(rollbackFor = Exception.class)
    public ActionResult upAccountPassword(@RequestBody JSONObject request){
        String account = request.getString("account");
        String oldPassword = request.getString("oldPassword");
        String newPassword = request.getString("newPassword");
        String decrypt = AESUtils.encrypt(oldPassword);
        String decrypt1 = AESUtils.encrypt(newPassword);
        UserPo userPo = userAccountService.selectAccount(account);
        String beforPassWord = userPo.getPassword();
        if(beforPassWord.equals(decrypt)){
            boolean b = userAccountService.upPassWord(account,decrypt1);
            if(b){
                return ActionResult.getSuccessResult("200");
            }
        }
        return ActionResult.getSuccessResult("5011");
    }

    /**
    * 重新发送激活邮件
    * @author ZhangZengZeng
    * @date 2023/3/31 20:27
    * @param account 账号
    * @return {@link ActionResult}
    */
    @GetMapping(value = "/tryActiveAccount/{account}")
    public ActionResult tryActiveAccount(@PathVariable(name = "account") String account,
                                         @PathParam("email") String email){
        log.info("tryActiveAccount 请求参数 账号:{},邮箱:{}",account,email);
        UserPo userPo = userAccountService.selectAccount(account);
        log.info("tryActiveAccount 查询用户返回:{}",userPo);
        if(!email.equals(userPo.getEmail())){
           return ActionResult.getSuccessResult("5009");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account",account);
        jsonObject.put("email",email);
        //重新激活缓存该账号激活凭证
        cache.put("ACTIVE"+account,account);
        rabbitTemplate.convertAndSend("loginEmail",jsonObject.toJSONString());
        return ActionResult.getSuccessResult("200");
    }

    @PostMapping(value = "/forgetToEmail")
    public ActionResult forgetToEmail(@RequestBody JSONObject jsonObject){
        String account = jsonObject.getString("account");
        String email = jsonObject.getString("email");
        log.info("forgetToEmail 请求参数 账号:{},邮箱:{}",account,email);
        boolean b = CheckUtils.checkEmail(email);
        String verificationCode = RandomStringUtils.randomNumeric(6);
        if(b){
            //邮箱
            boolean flag = userAccountService.checkEmailUse(email);
            if(!flag){
                return ActionResult.getSuccessResult("5013");
            }
            accountService.extracted(email,verificationCode);
        }else {
            UserPo userPo = userAccountService.selectAccount(account);
            if(userPo==null){
                return ActionResult.getSuccessResult("5010");
            }
            accountService.extracted(userPo.getEmail(),verificationCode);
        }
        return ActionResult.getSuccessResult("200");
    }

    @PostMapping(value = "/checkForgetToEmail")
    public ActionResult checkForgetToEmail(@RequestBody JSONObject jsonObject){
        String email = jsonObject.getString("email");
        String code = jsonObject.getString("code");
        String o = (String) cache.asMap().get(email + code);
        if(o!=null){
            String[] split = o.split(",");
            String mail = split[0];
            String cod = split[1];
            if(!mail.equals(email)){
                return ActionResult.getSuccessResult("5014");
            }
            if(cod.equals(code)){
                return ActionResult.getSuccessResult("5015");
            }
        }
        return ActionResult.getSuccessResult("200");
    }
}
